const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const { body, validationResult } = require('express-validator');
const { pool, testConnection, initDatabase } = require('./config/database');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 6000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 验证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: '访问令牌缺失' });
  }

  jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key', (err, user) => {
    if (err) {
      return res.status(403).json({ message: '无效的访问令牌' });
    }
    req.user = user;
    next();
  });
};

// 路由

// 注册
app.post('/api/register', [
  body('username').isLength({ min: 3 }).withMessage('用户名至少需要3个字符'),
  body('email').isEmail().withMessage('请输入有效的邮箱地址'),
  body('password').isLength({ min: 6 }).withMessage('密码至少需要6个字符')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { username, email, password } = req.body;

    // 检查用户是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT * FROM users WHERE username = ? OR email = ?',
      [username, email]
    );

    if (existingUsers.length > 0) {
      return res.status(400).json({ message: '用户名或邮箱已存在' });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建新用户
    const [result] = await pool.execute(
      'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
      [username, email, hashedPassword]
    );

    // 获取新创建的用户信息
    const [newUser] = await pool.execute(
      'SELECT id, username, email FROM users WHERE id = ?',
      [result.insertId]
    );

    // 生成JWT令牌
    const token = jwt.sign(
      { userId: newUser[0].id, username: newUser[0].username },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '24h' }
    );

    res.status(201).json({
      message: '注册成功',
      token,
      user: newUser[0]
    });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 登录
app.post('/api/login', [
  body('username').notEmpty().withMessage('用户名不能为空'),
  body('password').notEmpty().withMessage('密码不能为空')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { username, password } = req.body;

    // 查找用户
    const [users] = await pool.execute(
      'SELECT * FROM users WHERE username = ? OR email = ?',
      [username, username]
    );

    if (users.length === 0) {
      return res.status(400).json({ message: '用户名或密码错误' });
    }

    const user = users[0];

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password);

    if (!isValidPassword) {
      return res.status(400).json({ message: '用户名或密码错误' });
    }

    // 生成JWT令牌
    const token = jwt.sign(
      { userId: user.id, username: user.username },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '24h' }
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户信息
app.get('/api/user', authenticateToken, async (req, res) => {
  try {
    const [users] = await pool.execute(
      'SELECT id, username, email FROM users WHERE id = ?',
      [req.user.userId]
    );

    if (users.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }

    res.json({
      user: users[0]
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 登出
app.post('/api/logout', (req, res) => {
  res.json({ message: '登出成功' });
});

// 菜单API
const buildMenuTree = (flatMenus, parentId = null) => {
  return flatMenus
    .filter(item => item.parent_id === parentId)
    .sort((a, b) => a.order_num - b.order_num)
    .map(item => ({
      ...item,
      children: buildMenuTree(flatMenus, item.id)
    }));
};

// 获取菜单（树形结构）
app.get('/api/menus', async (req, res) => {
  try {
    const [menus] = await pool.execute('SELECT * FROM menu_items WHERE visible = 1');
    const tree = buildMenuTree(menus);
    res.json({ menus: tree });
  } catch (error) {
    console.error('获取菜单失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 新增菜单
app.post('/api/menus', authenticateToken, async (req, res) => {
  try {
    const { parent_id, label, icon, path, order_num, visible } = req.body;
    const [result] = await pool.execute(
      'INSERT INTO menu_items (parent_id, label, icon, path, order_num, visible) VALUES (?, ?, ?, ?, ?, ?)',
      [parent_id || null, label, icon, path, order_num || 0, visible === undefined ? 1 : visible]
    );
    res.status(201).json({ id: result.insertId });
  } catch (error) {
    console.error('新增菜单失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 修改菜单
app.put('/api/menus/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { parent_id, label, icon, path, order_num, visible } = req.body;
    await pool.execute(
      'UPDATE menu_items SET parent_id=?, label=?, icon=?, path=?, order_num=?, visible=? WHERE id=?',
      [parent_id || null, label, icon, path, order_num || 0, visible === undefined ? 1 : visible, id]
    );
    res.json({ message: '修改成功' });
  } catch (error) {
    console.error('修改菜单失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除菜单
app.delete('/api/menus/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    // 先删除所有子菜单
    await pool.execute('DELETE FROM menu_items WHERE parent_id=?', [id]);
    // 再删除自身
    await pool.execute('DELETE FROM menu_items WHERE id=?', [id]);
    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除菜单失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取所有用户（仅管理员）
app.get('/api/users', authenticateToken, async (req, res) => {
  try {
    // 这里只做简单演示，实际可加管理员判断
    const [users] = await pool.execute('SELECT id, username, email, created_at FROM users');
    res.json({ users });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 重置用户密码（仅管理员）
app.post('/api/users/:id/reset-password', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { newPassword } = req.body;
    if (!newPassword || newPassword.length < 6) {
      return res.status(400).json({ message: '新密码至少6位' });
    }
    const bcrypt = require('bcryptjs');
    const hashedPassword = await bcrypt.hash(newPassword, 10);
    await pool.execute('UPDATE users SET password=? WHERE id=?', [hashedPassword, id]);
    res.json({ message: '密码重置成功' });
  } catch (error) {
    console.error('重置密码失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取内容列表（含图片、评论）
app.get('/api/contents', async (req, res) => {
  try {
    const [contents] = await pool.execute('SELECT * FROM content_items ORDER BY created_at DESC');
    // 查询所有评论
    const [comments] = await pool.execute('SELECT * FROM content_comments ORDER BY created_at ASC');
    // 合并评论到内容
    const contentList = contents.map(item => ({
      ...item,
      images: item.images ? item.images.split(',').map(s => s.trim()).filter(Boolean) : [],
      comments: comments.filter(c => c.content_id === item.id)
    }));
    res.json({ contents: contentList });
  } catch (error) {
    console.error('获取内容失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 新增内容
app.post('/api/contents', authenticateToken, async (req, res) => {
  try {
    const { title, video_url, content, images } = req.body;
    await pool.execute(
      'INSERT INTO content_items (title, video_url, content, images) VALUES (?, ?, ?, ?)',
      [title, video_url, content, images || '']
    );
    res.status(201).json({ message: '添加成功' });
  } catch (error) {
    console.error('新增内容失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 修改内容
app.put('/api/contents/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { title, video_url, content, images } = req.body;
    await pool.execute(
      'UPDATE content_items SET title=?, video_url=?, content=?, images=? WHERE id=?',
      [title, video_url, content, images || '', id]
    );
    res.json({ message: '修改成功' });
  } catch (error) {
    console.error('修改内容失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除内容
app.delete('/api/contents/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    await pool.execute('DELETE FROM content_items WHERE id=?', [id]);
    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除内容失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ message: '服务器运行正常' });
});

// 启动服务器
const startServer = async () => {
  try {
    // 测试数据库连接
    await testConnection();
    
    // 初始化数据库表
    await initDatabase();
    
    // 启动服务器
    app.listen(PORT, () => {
      console.log(`🚀 服务器运行在端口 ${PORT}`);
      console.log(`📱 前端地址: http://localhost:3000`);
      console.log(`🔧 API地址: http://localhost:${PORT}/api`);
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
};

startServer(); 